Logoff Remote User

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
Clear-Host
Write-Host -Object '******************************'
Write-Host -Object '* Log Off User Remotely *'
Write-Host -Object '******************************'
Write-Host

$global:adminCreds = $host.ui.PromptForCredential('Need credentials', 'Please enter your user name and password.', '', '')
$global:ComputerName = Read-Host -Prompt 'Computer Name?'
Function get-usersessions 
{
  Write-Host
  Write-Host -Object 'Getting user sessions...'
  Write-Host
  Write-Host -Object '***************************************************************************'
  Invoke-Command -ComputerName $global:ComputerName -ScriptBlock {
    query.exe session
  } -Credential $global:adminCreds
}

Function start-userlogoff 
{
  Write-Host
  $SessionNum = Read-Host -Prompt 'Session ID number to log off?'
  $title = 'Log Off'
  $message = 'Are you sure you want to log them off?'
  $yes = New-Object -TypeName System.Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes', 'Logs selected user off.'
  $no = New-Object -TypeName System.Management.Automation.Host.ChoiceDescription -ArgumentList '&No', 'Exits.'
  $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)
  $result = $host.ui.PromptForChoice($title, $message, $options, 1)

  switch ($result){
    0 
    {
      Write-Host
      Write-Host -Object 'OK. Logging them off...'
      Invoke-Command -ComputerName $global:ComputerName -ScriptBlock {
        logoff.exe $args[0]
      } -ArgumentList $SessionNum -Credential $global:adminCreds
      Write-Host
      Write-Host -Object 'Success!' -ForegroundColor green
      break
    }
    1 
    {
      break
    }
  }
}

Do 
{
  get-usersessions
  start-userlogoff

  Write-Host
  #Write-Host "Press any key to continue ..."
  # $x = $host.UI.RawUI.ReadKey("NoEcho,IncludeKeyDown")

  #Configure yes choice
  $yes = New-Object -TypeName System.Management.Automation.Host.ChoiceDescription -ArgumentList '&Yes', 'Remove another profile.'

  #Configure no choice
  $no = New-Object -TypeName System.Management.Automation.Host.ChoiceDescription -ArgumentList '&No', 'Quit profile removal'

  #Determine Values for Choice
  $choice = [System.Management.Automation.Host.ChoiceDescription[]] @($yes, $no)

  #Determine Default Selection
  [int]$default = 0

  #Present choice option to user
  $userchoice = $host.ui.PromptforChoice('','Logoff Another Profile?',$choice,$default)
}
#If user selects No, then quit the script
Until ($userchoice -eq 1)